//
//  XJStatusPictureView.swift
//  新浪微博
//
//  Created by 徐绩 on 16/4/23.
//  Copyright © 2016年 ayumi. All rights reserved.
//

import UIKit

//item之间的间距
let XJStatusPictureItemMargin:CGFloat = 5
//item的宽高
let XJStatusPictureItemWH: CGFloat = {

    let intW = (SCREENW - 2 * cellMargin - 2 * XJStatusPictureItemMargin) / 3
    let floatW = CGFloat(intW)
    return floatW
}()

class XJStatusPictureView: UICollectionView {
    
    private let pictureCellID = "pictureCellID"
    
    //元祖类型
    var dataInfo: (pic_urls: [XJStatusUserInfo], size: CGSize)? {
    
        didSet{
        
            //如果是单图,设置itemSize为单图视图大小
            if dataInfo?.pic_urls.count == 1 {
                let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
                layout.itemSize = dataInfo?.size ?? CGSizeZero
                
            }else{
                //否则设置为原来的大小
                let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
                layout.itemSize = CGSizeMake(XJStatusPictureItemWH, XJStatusPictureItemWH)
                
            }
            
            self.snp_updateConstraints(closure: { (make) -> Void in
                
                make.size.equalTo(dataInfo?.size ?? CGSizeZero)
            })
            
            reloadData()
        }
    }


    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        backgroundColor = UIColor(white: 252/255, alpha: 1)
        registerClass(XJStatusPictureViewCell.self, forCellWithReuseIdentifier: pictureCellID)
        
       let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSizeMake(XJStatusPictureItemWH, XJStatusPictureItemWH)
        layout.minimumInteritemSpacing = XJStatusPictureItemMargin
        layout.minimumLineSpacing = XJStatusPictureItemMargin
        
        self.dataSource = self
        self.delegate = self
    }

}
// MARK: - CollectionView数据源,代理方法实现
extension XJStatusPictureView:UICollectionViewDataSource ,UICollectionViewDelegate{

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataInfo?.pic_urls.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureCellID, forIndexPath: indexPath) as! XJStatusPictureViewCell
        
        cell.photoInfo = dataInfo?.pic_urls[indexPath.item]
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        //仿照框架中的demo
        let photoBrowser = SDPhotoBrowser()
        photoBrowser.delegate = self
        photoBrowser.currentImageIndex = indexPath.item
        photoBrowser.imageCount = dataInfo!.pic_urls.count
        photoBrowser.sourceImagesContainerView = self
        photoBrowser.show()
    }
    
}
// MARK: - SDPhotoBrowserDelegate
extension XJStatusPictureView: SDPhotoBrowserDelegate{

    //占位图
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        let cell = self.cellForItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0))! as! XJStatusPictureViewCell
        
        return cell.imageView.image
    }
    //返回高清图
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        
        let urlStr = dataInfo!.pic_urls[index].thumbnail_pic!.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        return NSURL(string: urlStr)
    }
}

/// 自定义cell
class XJStatusPictureViewCell: UICollectionViewCell {
    
    var photoInfo: XJStatusUserInfo? {
    
        didSet{
            imageView.sd_setImageWithURL(NSURL(string: photoInfo?.thumbnail_pic ?? ""),placeholderImage:(UIImage(named: "timeline_image_placeholder")))
            
            gifImgView.hidden = !(photoInfo?.thumbnail_pic ?? "").hasSuffix(".gif")
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /**
     布局界面
     */
    private func setupUI(){
        
        contentView.addSubview(imageView)
        contentView.addSubview(gifImgView)
        
        imageView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(contentView)
        }
        gifImgView.snp_makeConstraints { (make) -> Void in
            
            make.trailing.bottom.equalTo(contentView)
        }
    }
    
    /// 懒加载控件
   private lazy var imageView: UIImageView = {
    
        let imgView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        imgView.contentMode = .ScaleAspectFill
        imgView.clipsToBounds = true
    
        return imgView
    }()
    
    private lazy var gifImgView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
}
